package com.waa.gulimall.ware.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class MyRabbitConfig {

    /**
     * 使用json序列化机制，进行消息转换
     * @return
     */
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }

    @Bean
    public Exchange stockEventExchange(){
        return ExchangeBuilder.topicExchange("stock-event-exchange").durable(true).build();
    }
    @Bean
    public Queue stockReleaseStockQueue(){
        return QueueBuilder.durable("stock.release.stock.queue").build();
    }
    @Bean
    public Queue stockDelayQueue(){
        Map<String, Object> args = new HashMap<>(3);
        //声明当前队列绑定的死信交换机
        args.put("x-dead-letter-exchange", "stock-event-exchange");
        //声明当前队列的死信路由 key
        args.put("x-dead-letter-routing-key", "stock.release.#");
        //声明队列的 TTL
        args.put("x-message-ttl", 180000);
        return QueueBuilder.durable("stock.delay.queue").withArguments(args).build();
    }

    @Bean
    public Binding stockReleaseBinding(@Qualifier("stockReleaseStockQueue") Queue stockReleaseStockQueue,
                                       @Qualifier("stockEventExchange") Exchange stockEventExchange){
        return BindingBuilder.bind(stockReleaseStockQueue).to(stockEventExchange).with("stock.release.#").noargs();
    }
    @Bean
    public Binding stockLockedBinding(@Qualifier("stockDelayQueue") Queue stockDelayQueue,
                                       @Qualifier("stockEventExchange") Exchange stockEventExchange){
        return BindingBuilder.bind(stockDelayQueue).to(stockEventExchange).with("stock.locked").noargs();
    }
}
